package com.cyx.netty.gateway.config;

import com.cyx.netty.gateway.util.cache.ChannelCacheManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {
  private int lossConnectCount = 0;

  @Override
  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

    log.info("已经***秒未收到客户端的消息了！");
    if (evt instanceof IdleStateEvent){
      IdleStateEvent event = (IdleStateEvent)evt;
      if (event.state()== IdleState.READER_IDLE){
        lossConnectCount++;
        if (lossConnectCount>3){

          log.info("关闭这个服务端不活跃通道！");
          ChannelCacheManager.remove(ctx.channel().id().asShortText());
          ctx.channel().close();
        }
      }
    }else {
      super.userEventTriggered(ctx,evt);
    }
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg)  {
    lossConnectCount = 0;
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)  {
    ctx.close();
  }
}
